# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import logging,time

def on_connect( client, userdata, flags, rc ):
    userdata.on_connect(flags,rc)

def on_subscribe(client, userdata, mid, granted_qos):
    userdata.on_subscribe(mid,granted_qos)

def on_unsubscribe(client, userdata, mid):
    userdata.on_unsubscribe(mid)

def on_disconn( client, userdata, rc ):
    userdata.on_disconn(rc)

def on_message( client, userdata, msg ):
    userdata.on_message(msg)

class DcBase:
    step = 'uncon'
    appname = 'test'
    client = None

    def run(self,host,port):
        self.client = mqtt.Client(userdata=self)
        self.client.on_connect = on_connect
        self.client.on_subscribe = on_subscribe
        self.client.on_unsubscribe = on_unsubscribe
        self.client.on_disconnect = on_disconn
        self.client.on_message = on_message

        logging.info(u'连接服务器:%s:%s'%(host,port))
        self.client.connect(host, port, 10)
        self.client.loop_start()

    def on_connect(self,flags,rc):
        logging.debug(u'连接成功')
        self.step = 'conn'

    def on_subscribe(self,mid, granted_qos):
        logging.debug(u'订阅成功')
        self.step = 'subed'

    def on_unsubscribe(self,mid):
        logging.debug(u'退订成功')
        self.step = 'usub'

    def on_disconnect(self,rc):
        logging.debug(u'连接断开')
        raise SystemExit(2)

    def on_message(self,msg):
        logging.info("%s->message:%s---%s"%(self.step,msg.topic,msg.payload))

    def checkStep(self,state,timeout=10):
        u'测试状态'
        lastStep = self.step

        secs = time.clock()
        while lastStep!=state:
            if lastStep!=self.step:
                logging.debug(u'状态变化%s->%s'%(lastStep,self.step))
                lastStep = self.step

            if (time.clock()-secs)>timeout:
                logging.debug(u'状态(%s)%s超时%s'%(self.step,state,timeout))
                return False
        return True

    def subscribe(self,topic,timeout=10):
        self.step = 'sub'
        self.client.subscribe(topic)
        return self.checkStep('subed',timeout)

    def unsubscribe(self,topic,timeout=10):
        self.step = 'usub'
        self.client.unsubscribe(topic)
        return self.checkStep('usub')

    def publish(self,topic,msg,qos=None):
        self.step = "pub"
        return self.client.publish(topic, msg)[0]==0
